package com.itlangzi.mybatis.page;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 分页对象
 */
public class Pagination<T> {

    /**当前页*/
    private int page;
    /**每页的大小*/
    private int size;
    /**总记录数*/
    private int totalElements;
    /**总页数*/
    private int totalPages;

    private List<T> content = new ArrayList<>();

    public Pagination() {
        super();
    }

    public Pagination(int page, int size) {
        super();
        this.setPage(page);
        this.setSize(size);
    }


    public Pagination(int page, int size, int totalElements, List<T> content) {
        super();
        this.setSize(size);
        this.setPage(page);
        this.setTotalElements(totalElements);
        this.content = content;
        this.totalPages = calcTotalPage();
    }


    public int getPage() {
        return page;
    }

    public int getSize() {
        return size;
    }

    public void setPage(int page) {
        this.page = page <= 0 ? 0 : page;
    }

    public void setSize(int size) {
        this.size = size <= 0 ? 0 : size;
    }

    public int getTotalElements() {
        return totalElements;
    }

    public void setTotalElements(int totalElements) {
        this.totalElements = totalElements <= 0 ? 0 : totalElements;
        this.totalPages = calcTotalPage();
    }

    public int getTotalPages() {
        return totalPages;
    }

    public List<T> getContent() {
        return this.content;
    }

    public void setContent(List<T> content) {
        this.content = content;
    }

    public void add(T t) {
        this.content.add(t);
    }

    public void addAll(List<T> content) {
        this.content.addAll(content);
    }
    public boolean hasNext() {
        return this.getPage() + 1 < this.getTotalPages();
    }
    public boolean hasPrevious() {
        return this.getPage() > 0;
    }
    public boolean isFirst() {
        return !this.hasPrevious();
    }

    public boolean isLast() {
        return !this.hasNext();
    }
    public boolean hasContent() {
        return !this.content.isEmpty();
    }
    public Iterator<T> iterator() {
        return this.content.iterator();
    }

    private int calcTotalPage() {
        if (this.totalElements > 0 && this.size > 0) {
            return this.totalElements % this.size == 0 ? this.totalElements / this.size : this.totalElements / this.size + 1;
        }
        return 0;
    }

}
